#!/usr/bin/env python
import email

from google.appengine.ext.webapp import RequestHandler
from google.appengine.api import users
from google.appengine.ext import db

from templates import run, render, redirect, out
from models import UserActions, Friends
from sessions import Session

class Add(RequestHandler):
    session = Session()
    def post(self):
        user = users.get_current_user()
        if not self.request.get('friendname') or not self.request.get('friendemail'):
            if not self.request.get('friendname'):
                self.session['friendname'] = 'Friend needs a name!'

            if not self.request.get('friendemail'):
                self.session['friendemail'] = 'Need friend\'s email!'

            redirect(self,'/home')			
        else:
            user = users.get_current_user()
            fr = Friends(email=user, friendEmail=self.request.get('friendemail'), friendNickname=self.request.get('friendname'), approved=0)
            fr.put()
            redirect(self, '/home')


class Delete(RequestHandler):
    session = Session()
    
    def post(self):
        if users.get_current_user():
            user = users.get_current_user()
            fr = Friends.gql('WHERE email = :1 AND friendEmail = :2', user, self.request.get('email')).get()
            fr.delete()
        else:
            pass
        
        friends = Friends.all()	
        friends.filter('email = ', user)
        friends.filter('approved = ', 1)

        pendingfriends = Friends.all()
        pendingfriends.filter('friendEmail = ', user.email())
        pendingfriends.filter('approved = ', 0)

        render(self, 'ajax/friendlist.html', values = {'friends':friends, 'pendingfriends':pendingfriends})

class ApproveFriend(RequestHandler):
    def post(self):
        if users.get_current_user():
            user = users.get_current_user()
            friendUser = users.User(self.request.get('email'))
            pFriend = Friends.gql('WHERE friendEmail = :1 AND email = :2', user.email(), friendUser).get()
            pFriend.approved = 1
            pFriend.put()

            fr = Friends(email=user, friendEmail=friendUser.email(), approved=1, friendNickname=friendUser.nickname())
            fr.put()

        else:
            pass
        
        friends = Friends.all()	
        friends.filter('email = ', user)
        friends.filter('approved = ', 1)

        pendingfriends = Friends.all()
        pendingfriends.filter('friendEmail = ', user.email())
        pendingfriends.filter('approved = ', 0)

        render(self, 'ajax/friendlist.html', values = {'friends':friends, 'pendingfriends':pendingfriends})
        
        
class DisapproveFriend(RequestHandler):
    def post(self):
        pass
    

if __name__ == '__main__':
    run([('/friends/add', Add), ('/friends/delete', Delete), ('/friends/disapprovefriend', DisapproveFriend), ('/friends/approvefriend', ApproveFriend)])